clear;clc;clf; close all;

%% Building block-LM
%%
mws = CST_Initilization;
tic;
CST_Modeling(mws);
disp(["建模成功，所用时间为：", num2str(toc), 'S']);

%% 建模函数
function [] = CST_Modeling(mws)

    Frq = [0.5, 2]; % 工作频率,太赫兹波波长范围是3mm-30um
    FC_Property_Setup_Simplfied(mws, Frq, "time");
    % 仿真参数设置

    CST_Post = CST_MicrowaveStudio();
    % down 部分参数设置
    Px = 400; %结构X向边长
    Py = 400; %结构Y向边长
    Sy = 130; %被减去的Y向边长
    Sz = 50; %被减去的Z向边长
    Sx = 50; %x方向偏移量
    MetalThick = 0.2; %基地层金属厚度
    H = 140; % 立柱高度
    DielectThick_down = 180; % 树脂的厚度
    BaseGround_down = 20; % 树脂基层到金属的厚度
    W_down = 40;
    L_down = 310;

    CST_Post.addParameter('Px', Px);
    CST_Post.addParameter('Py', Py);
    CST_Post.addParameter('Sx', Sx);
    CST_Post.addParameter('Sy', Sy);
    CST_Post.addParameter('Sz', Sz);
    CST_Post.addParameter('H', H);
    CST_Post.addParameter('MetalThick', MetalThick);
    CST_Post.addParameter('DielectThick_down', DielectThick_down);
    CST_Post.addParameter('BaseGround_down', BaseGround_down);
    CST_Post.addParameter('W_down', W_down);
    CST_Post.addParameter('L_down', L_down);

    DH = 0; DW = 0;
    invoke(mws, 'StoreParameter', 'DH ', DH);
    invoke(mws, 'StoreParameter', 'DW ', DW);

    % up 部分参数设置

    L_up1 = 200;
    DielectThick_up = 100;
    W_up = 60;
    BaseGround_up = 20; % 树脂基层到金属的厚度
    CST_Post.addParameter('DielectThick_up', DielectThick_up);
    CST_Post.addParameter('BaseGround_up', BaseGround_up);
    CST_Post.addParameter('W_up', W_up);
    CST_Post.addParameter('L_up1', L_up1);

    % 组件
    FC_New_Component(mws, "介质");
    FC_New_Component(mws, "金属");

    % step 1. 建立底层基底
    FC_Model_Brick(mws, '-Px / 2', 'Px / 2', '-Py / 2', 'Py / 2', '-MetalThick', '0', 'Cu_YW', '金属', '基底');

    % step 2. 建立树脂 down
    FC_Model_Brick(mws, '-Px / 2', 'Px / 2', '-Py / 2', 'Py / 2', '0', 'DielectThick_up', 'HTL_YW', '介质', '树脂块');
    FC_Model_Brick(mws, '-Px / 2', 'Px / 2', '-Sy / 2', 'Sy / 2', 'DielectThick_up', 'DielectThick_up+Sz', 'HTL_YW', '介质', '突出树脂块');

    for roundtime = 1:2
        % step 3. 建立金属条
        % step 3.1 X方向流道
        FC_Model_Brick(mws, '-Px / 2', 'Px / 2', '-W_up/2', 'W_up/2', 'BaseGround_up', 'W_up+BaseGround_up', 'Cu_YW', '金属', '金属条_X方向流道');
        % step 3.2 Y方向金属条
        FC_Model_Brick(mws, '-W_up / 2-Sx', 'W_up / 2-Sx', '-L_up1/2', 'L_up1/2', 'BaseGround_up', 'W_up+BaseGround_up', 'Cu_YW', '金属', '金属条_Y顶部');

        if roundtime == 1

            % Step 4. bool运算减去金属条
            CST_Post.subtractObject("介质:树脂块", "金属:金属条_X方向流道");
            CST_Post.subtractObject("介质:树脂块", "金属:金属条_Y顶部");

        end

    end

end

%% 调用CSTStudio并初始化
function mws = CST_Initilization()
    path = pwd; % 获取当前m文件夹路径
    cst = actxserver('CSTStudio.application');
    mws = invoke(cst, 'NewMWS');
    % app = invoke(mws, 'GetApplicationName');
    % ver = invoke(mws, 'GetApplicationVersion');
    invoke(mws, 'FileNew');
    invoke(mws, 'DeleteResults'); % 删除之前的结果，防止程序停止运行

end
